package com.rxgscd.yy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;

import com.alipay.sdk.app.PayTask;
import com.sdk.API;
import com.sdk.AuthResult;
import com.sdk.CommonDefine;
import com.sdk.HttpUtils;
import com.sdk.JsonParser;
import com.sdk.PayResult;
import com.sdk.SDKUtility;
import com.sdk.WxpayUtils;

import com.appsflyer.AFInAppEventParameterName;
import com.appsflyer.AFInAppEventType;
import com.appsflyer.AppsFlyerLib;
import com.quickgame.android.sdk.utils.log.QGLog;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.game.UMGameAgent;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.core.content.FileProvider;

import android.text.TextUtils;
import android.util.Log;
import android.view.DisplayCutout;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;


import com.quickgame.android.sdk.QuickGameManager;
import com.quickgame.android.sdk.QuickGameManager.QGPaymentCallback;
import com.quickgame.android.sdk.QuickGameManager.SDKCallback;
import com.quickgame.android.sdk.bean.QGOrderInfo;
import com.quickgame.android.sdk.bean.QGRoleInfo;
import com.quickgame.android.sdk.bean.QGUserData;
import com.quickgame.android.sdk.model.QGUserHolder;
import com.unity3d.player.UnityPlayerActivity;

public class MainActivity extends UnityPlayerActivity {
    public static MainActivity instance;
    public static String APP_ID = "wx15d244c8734a33f0";// 微信APPID
    public static String AppSecret = "a157374df39c737c3f4cbc27762782e3";// 微信密钥
    public static String Partnerid = "1565070061";// 微信商户号
    public static String SIGNKEY = "jkd1dss12s58s2f1d2assss5w2sf59df";// 微信签名密钥
    public static MyHandler myHandler;
    private IWXAPI wxapi;
    public String access_token;
    public String openid;
    public String refresh_token;
    private int mTargetScene = SendMessageToWX.Req.WXSceneSession;
    private static final int THUMB_SIZE = 150;

    private Context mContext; // 上下文
//    @SuppressLint("SdCardPath")
//	private static final String savePath = "/sdcard/updateAPK/";//"/sdcard/updateAPK/"; //apk保存到SD卡的路径
//    private static final String saveFileName = savePath + "Mir2TeJie.apk"; //完整路径名

    private static final int DOWNLOADING = 100; // 表示正在下载
    private static final int DOWNLOADED = 101; // 下载完毕
    private static final int DOWNLOAD_FAILED = 102; // 下载失败
    private int progress; // 下载进度
    private boolean cancelFlag = false; // 取消下载标志位

    private static BroadcastReceiver batteryLevelRcvr;
    private static IntentFilter batteryLevelFilter;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private OrientationEventListener moriLister;
    private int oriNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        regToWx();
        myHandler = new MyHandler();
        mContext = this;

        MonitorBatteryState();

//		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
//			getNotchInfo();
//			DisplayFullScreen();
//		}
//		else {
        StartScreenAdapation(mContext);
//		}
        //ListerOri();
        S_init_sdk();

    }

    void S_init_sdk() {
        //sdk初始化
        SampleSDKCallback sdkCallback = new SampleSDKCallback();
        sdkInstance = QuickGameManager.getInstance();
        sdkInstance.init(this, Parameter.Product_Code, sdkCallback);
        sdkInstance.onCreate(this);
        if (isPrintFBlog) {
            Log.i(fbLog, "FB初始化 init");
        }
    }

    /*
     * 检测手机横竖屏
     */
    private void ListerOri() {
        moriLister = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
            @Override
            public void onOrientationChanged(int orientation) {
                if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
                    return;
                }
                Log.i("UNITY", "ListerOri orientation:" + orientation);

                if (orientation > 350 || orientation < 10) {
                    oriNum = 0;
                } else if (orientation > 80 && orientation < 100) {
                    oriNum = 90;
                } else if (orientation > 170 && orientation < 190) {
                    oriNum = 180;
                } else if (orientation > 260 && orientation < 280) {
                    oriNum = 270;
                } else {
                    return;
                }
                Log.i("UNITY", "ListerOri oriNum:" + oriNum);
                SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.OrientationCallBack, String.valueOf(oriNum));
            }
        };

        if (moriLister.canDetectOrientation()) {
            moriLister.enable();
        } else {
            moriLister.disable();
        }
    }

    /// 注册到微信
    private void regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        wxapi = WXAPIFactory.createWXAPI(this, APP_ID, true);

        // 将应用的appId注册到微信
        wxapi.registerApp(APP_ID);

        // 建议动态监听微信启动广播进行注册到微信
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // 将该app注册到微信
                wxapi.registerApp(APP_ID);
            }
        }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
    }

    /// 获取微信Code
    private void SendReq() {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "none";
        wxapi.sendReq(req);
        Log.i("UNITY", "SendReq over");
    }

    public class MyHandler extends Handler {
        public MyHandler() {

        }

        public MyHandler(Looper L) {
            super(L);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case SDKUtility.SDKFUNTYPE.INIT: {
                    Log.i("UNITY", "call com.sdk init function");
                }
                break;
                case SDKUtility.SDKFUNTYPE.GETAPKVERSION: {
                    Log.i("UNITY", "call com.sdk getapkversion1 function");
                    GetApkVersion();
                    Log.i("UNITY", "call com.sdk getapkversion1 function");
                }
                break;
                case SDKUtility.SDKFUNTYPE.UPDATEGAME: {
                    Log.i("UNITY", "call com.sdk updategame1 function");
                    // downloadAPK();
                    installAPK();
                    Log.i("UNITY", "call com.sdk updategame2 function");
                }
                break;
                case SDKUtility.SDKFUNTYPE.LOGIN: {
                    Log.i("UNITY", "call com.sdk login1 function");
                    //微信登陆的
//				if (wxapi.isWXAppInstalled()) {
//					SendReq();
//				} else {
//					Toast.makeText(mContext, "请先安装微信客户端", 2);
//				}

                    //台湾登陆的
                    FBLogin();
                    Log.i("UNITY", "call com.sdk login2 function");
                }
                break;
                case SDKUtility.SDKFUNTYPE.SETOPENLOG: {
                    Log.i("UNITY", "call com.sdk setopenlog function");
                }
                break;
                case SDKUtility.SDKFUNTYPE.GETPLATFORM: {
                    Log.i("UNITY", "call com.sdk getplatform function");
                }
                break;
                case SDKUtility.SDKFUNTYPE.SENDROLEINFO: {
                    Log.i("UNITY", "call com.sdk sendroleinfo function");
                }
                break;
                case SDKUtility.SDKFUNTYPE.PAY: {
                    try {
                        Pay();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("UNITY", "call com.sdk pay function e =-= " + e);
                    }
                    Log.i("UNITY", "call com.sdk pay function");
                }
                break;
                case SDKUtility.SDKFUNTYPE.ZHIFUBAOPAY:
                    try {
                        zhifubaoPay();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("UNITY", "call com.sdk zhifubaoPay function e =-= " + e);
                    }
                    Log.i("UNITY", "call com.sdk zhifubaoPay function");
                    break;
                case SDKUtility.SDKFUNTYPE.SHARE: {
                    Log.i("UNITY", "call com.sdk share function");
                }
                break;
                case SDKUtility.SDKFUNTYPE.ONPROFILESIGNIN: {
                    try {
                        UMGameAgent.onProfileSignIn(API.Provider, API.PlayerId);
                        Log.i("UNITY", "call com.sdk ONPROFILESIGNIN function");
                    } catch (Exception e) {
                        Log.i("UNITY", "SDKUtility.SDKFUNTYPE.ONPROFILESIGNIN ==" + e.toString());
                    }
                }
                break;
                case SDKUtility.SDKFUNTYPE.ONPROFILESIGNOFF: {
                    try {
                        UMGameAgent.onProfileSignOff();
                        Log.i("UNITY", "call com.sdk ONPROFILESIGNOFF function");
                    } catch (Exception e) {
                        Log.i("UNITY", "SDKUtility.SDKFUNTYPE.ONPROFILESIGNOFF ==" + e.toString());
                    }
                }
                break;
                case SDKUtility.SDKFUNTYPE.UMENGPAY: {
                    try {
                        UMGameAgent.pay(API.MoneyCount, API.DiamondCount, 21);
                        Log.i("UNITY", "call com.sdk UMENGPAY function");
                    } catch (Exception e) {
                        Log.i("UNITY", "SDKUtility.SDKFUNTYPE.UMENGPAY ==" + e.toString());
                    }
                }
                break;
                case SDKUtility.SDKFUNTYPE.LOGOUT: {
                    Log.i("UNITY", "call com.sdk logout function");
                    FBLogout();
                }
                break;
                case SDKUtility.SDKFUNTYPE.QGPAY: {
                    Log.i("UNITY", "call com.sdk QGPAY function");
                    if (API.qgOrderInfo != null && API.qgRoleInfo != null) {
                        FBPay(API.qgOrderInfo, API.qgRoleInfo);
                    }
                }
                break;
                case SDKUtility.SDKFUNTYPE.QGROLE: {
                    Log.i("UNITY", "call com.sdk QGROLE function");
                    if (API.qgRoleInfo != null) {
                        FBUpdateRoleInfo(API.qgRoleInfo);
                    }
                }
                break;
                case SDKUtility.SDKFUNTYPE.QGCreateRole: {
                    Log.i("UNITY", "call com.sdk QGROLE function");
                    if (API.creteRoleId != null) {
                        FBCreateRoleFinished(API.creteRoleId);
                    }
                }
                break;
                case DOWNLOADING:
                    break;
                case DOWNLOADED:
                    installAPK();
                    break;
                case DOWNLOAD_FAILED:
                    Toast.makeText(mContext, "网络断开，请稍候再试", Toast.LENGTH_LONG).show();
                    break;
                case SDKUtility.SDKFUNTYPE.UMReport:
                    try {
                        if ("Report_PayData".equals(API.m_EventId)) {
                            FBReportAppPay(API.qgOrderInfo.getProductOrderId(), API.qgOrderInfo.getAmount(), API.qgOrderInfo.getOrderSubject(), API.qgOrderInfo.getGoodsId());
                        }
                        if (API.m_EventData.contains("_")) {
                            HashMap<String, String> map = new HashMap<String, String>();
                            if (API.m_EventData.contains(",")) {
                                String[] ss = API.m_EventData.split(",");
                                if (ss != null && ss.length > 0) {
                                    for (int i = 0; i < ss.length; i++) {
                                        String[] ss1 = API.m_EventData.split("_");
                                        map.put(ss1[0], ss1[1]);
                                    }
                                }
                            } else {
                                String[] ss = API.m_EventData.split("_");
                                if (ss != null && ss.length > 0) {
                                    map.put(ss[0], ss[1]);
                                }
                            }

                            UMGameAgent.onEvent(mContext, API.m_EventId, map);
                        } else {
                            UMGameAgent.onEvent(mContext, API.m_EventId, API.m_EventData);
                        }

                        Log.i("UNITY", "call com.sdk m_EventId = " + API.m_EventId + "  m_EventData == " + API.m_EventData);
                    } catch (Exception e) {
                        Log.i("UNITY", "SDKUtility.SDKFUNTYPE.UMReport ==" + e.toString());
                    }
                    break;
            }
        }
    }

    public void GetApkVersion() {
        try {
            PackageInfo pkgInfo = getPackageManager().getPackageInfo(getApplication().getPackageName(), 0);
            String versionString = pkgInfo.versionName;
            SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.GETVERSIONCALLBACK, versionString);
            Log.i("UNITY", "versionString == " + versionString);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    /**
     * 判断是否有网络连接
     */
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    private boolean isFinish = false;

    /**
     * 下载apk的线程
     */
    public void downloadAPK() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(API.UpdateUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();

                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    int count = 0;
                    Log.i("UNITY", "00000000000");
                    File ApkFile = new File(getExternalFilesDir(null), "Mir2TeJie.apk");
                    Log.i("UNITY", "111111111111");
                    FileOutputStream fos = new FileOutputStream(ApkFile);
                    Log.i("UNITY", "8888888888888888");
                    byte buf[] = new byte[1024];

                    do {
                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        // myHandler.sendEmptyMessage(DOWNLOADING);
                        SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.DOWNLOADCALLBACK,
                                count + "|" + length + "|" + progress);
                        if (numread <= 0) {
                            // 下载完成通知安装
                            Log.i("UNITY", "2222222222222");
                            isFinish = true;
                            myHandler.sendEmptyMessage(DOWNLOADED);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (!cancelFlag); // 点击取消就停止下载.

                    fos.close();
                    is.close();
                } catch (Exception e) {
                    myHandler.sendEmptyMessage(DOWNLOAD_FAILED);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 下载完成后自动安装apk
     */
    public void installAPK() {
        Log.i("UNITY", "33333333333333333 API.UpdateUrl ==" + API.UpdateUrl);
        // File apkFile = new File(getExternalFilesDir(null), "Mir2TeJie.apk");
        File apkFile = new File(API.UpdateUrl);
        if (!apkFile.exists()) {
            return;
        }
        Log.i("UNITY", "444444444444444");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 授予临时权限别忘了
            Log.i("UNITY", "mContext == " + mContext);
            Log.i("UNITY", "mContext.getPackageName() == " + mContext.getPackageName());
            Log.i("UNITY", "apkFile == " + apkFile + "       apkFile.getName() == " + apkFile.getName());
            Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Log.i("UNITY", "55555555555555");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            Log.i("UNITY", "6666666666666666");
        }
        mContext.startActivity(intent);
        Log.i("UNITY", "7777777777777777777");
    }

    /// 获取Tocken
    public void getAccessToken(final String code) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=" + APP_ID + "&secret="
                        + AppSecret + "&code=" + code + "&grant_type=authorization_code";

                Log.i("UNITY", "start getAccessToken   url = " + url);

                String ret = HttpUtils.httpGet(url);
                Log.i("UNITY", "start getAccessToken   ret = " + ret);
                JSONObject jObg = null;
                try {
                    jObg = new JSONObject(ret);
                    Log.i("Unity", "发送成功1 + jObg==" + jObg);
                    access_token = JsonParser.getString(jObg, "access_token");
                    refresh_token = JsonParser.getString(jObg, "refresh_token");
                    openid = JsonParser.getString(jObg, "openid");

                    InvalidTocken();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.i("Unity", "发送成功 2+ ret==" + ret);

            }
        }).start();
    }

    /// 校验Tocken是否有效
    public void InvalidTocken() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                String url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;

                Log.i("UNITY", "start InvalidTocken   url = " + url);
                String ret = HttpUtils.httpGet(url);
                Log.i("Unity", "start InvalidTocken   ret = " + ret);
                JSONObject jObg = null;
                try {
                    jObg = new JSONObject(ret);
                    Log.i("Unity", "校验1 + jObg==" + jObg);

                    if (!JsonParser.getString(jObg, "errcode").equals("0")) {
                        Log.i("Unity", "校验2 + errcode!=0");
                        getRefreshTocken();
                    } else {
                        Log.i("Unity", "校验3 + errcode==0");
                        GetTockenSuccess();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    /// 刷新Tocken
    public void getRefreshTocken() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?" + "appid=" + APP_ID
                        + "&grant_type=refresh_token" + "&refresh_token=" + refresh_token;

                Log.i("UNITY", "start getRefreshTocken   url = " + url);
                String ret = HttpUtils.httpGet(url);
                Log.i("Unity", "start getRefreshTocken   ret = " + ret);
                JSONObject jObg = null;
                try {
                    jObg = new JSONObject(ret);
                    Log.i("Unity", "刷新tocken1 + jObg==" + jObg);

                    access_token = JsonParser.getString(jObg, "access_tocken");
                    refresh_token = JsonParser.getString(jObg, "refresh_token");
                    openid = JsonParser.getString(jObg, "openid");
                    GetTockenSuccess();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.i("Unity", "start getRefreshTocken2 ");
            }
        }).start();
    }

    /// 获取Tocken之后向Unity回调
    public void GetTockenSuccess() {
        SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.LOGINCALLBACK, access_token + "|" + openid);
        Log.i("Unity", "向Unity发送消息 + access_token==" + access_token + "      openid == " + openid);
    }

    /// 微信支付
    public void Pay() {
        Log.i("UNITY", "开始调用SDK支付接口");
        final PayReq requestPayReq = new PayReq();
        requestPayReq.appId = APP_ID;// 应用ID

        requestPayReq.partnerId = Partnerid;// 商户号
        requestPayReq.prepayId = API.PrepayId;// 预支付交易会话ID
        Log.i("UNITY", "生成的支付信息预支付交易会话ID== " + requestPayReq.prepayId);

        requestPayReq.packageValue = "Sign=WXPay";// 扩展字段

        String noString = UUID.randomUUID().toString().replace("-", "");
        requestPayReq.nonceStr = noString;// API.NonceStr;//随机字符串
        Log.i("UNITY", "生成的支付信息随机字符串== " + requestPayReq.nonceStr);

        String timeString = String.valueOf(System.currentTimeMillis() / 1000);
        requestPayReq.timeStamp = timeString;// 时间戳
        Log.i("UNITY", "生成的支付信息时间戳== " + requestPayReq.timeStamp);

        HashMap<String, String> mHashMap = new HashMap<String, String>();
        mHashMap.put("appid", APP_ID);
        mHashMap.put("partnerid", Partnerid);
        mHashMap.put("prepayid", API.PrepayId);
        mHashMap.put("package", "Sign=WXPay");
        mHashMap.put("noncestr", noString);
        mHashMap.put("timestamp", timeString);
        try {
            String signString = WxpayUtils.Sign(mHashMap, SIGNKEY);
            if (signString != null && signString != "") {
                requestPayReq.sign = signString;
                Log.i("UNITY", "生成的支付信息签名== " + requestPayReq.sign);
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } // 签名

        wxapi.sendReq(requestPayReq);
        Log.i("UNITY", "调用SDK支付接口完成");
    }

    /// 获取用户信息
    public void GetUserInfo() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                String url = "https://api.weixin.qq.com/sns/userinfo?access=" + access_token + "&openid=" + openid;
                Log.i("UNITY", "start GetUserInfo   url = " + url);

                String ret = HttpUtils.httpGet(url);
                Log.i("Unity", "start getRefreshTocken   ret = " + ret);
                JSONObject jObg = null;
                try {
                    jObg = new JSONObject(ret);
                    Log.i("Unity", "获取用户信息1 + jObg==" + jObg);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void zhifubaoPay() {
        final String orderInfo = API.OrderInfo;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(MainActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.PAYCALLBACK, "0");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.PAYCALLBACK, "-1");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(MainActivity.this, "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(MainActivity.this, "授权失败" + String.format("authCode:%s", authResult.getAuthCode()),
                                Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    /**
     * 检查用户是用的 Wifi 还是 流量
     */
    public boolean isWifiOrTraffic() {
        boolean isWifitrue = false;
        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressWarnings("deprecation")
        NetworkInfo mWifiInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        isWifitrue = mWifiInfo.isConnected();
        return isWifitrue;
    }

    /**
     * 检查用户MOBILE网络是否可用
     */
    public boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            @SuppressWarnings("deprecation")
            NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * Wifi的连接速度及信号强度
     */
    public int obtainWifiInfo() {
        int strength = 0;
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); // 取得WifiManager对象
        WifiInfo info = wifiManager.getConnectionInfo(); // 取得WifiInfo对象
        if (info.getBSSID() != null) {
            strength = WifiManager.calculateSignalLevel(info.getRssi(), 5); // 链接信号强度，5为获取的信号强度值在5以内
            // int speed = info.getLinkSpeed(); // 链接速度
            // String units = WifiInfo.LINK_SPEED_UNITS; // 链接速度单位
            // String ssid = info.getSSID(); // Wifi源名称
        }
        return strength; // return info.toString();
    }

    public BroadcastReceiver rssiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("Rssi", "=====RSSI changed");
            if (isWifiOrTraffic()) {
                setWifiStrength(obtainWifiInfo());
            }

//			if (isNetworkConnected(mContext) && !isFinish) {
//				downloadAPK();
//			}
        }
    };

    public void setWifiStrength(int strength) {
        SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.WIFISTATECALLBACK, strength + "");
    }

    /**
     * 1.获取手机电池电量 2.检查手机是否充电
     */
    public void MonitorBatteryState() {
        batteryLevelRcvr = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                int rawlevel = intent.getIntExtra("level", -1);
                int scale = intent.getIntExtra("scale", -1);
                int status = intent.getIntExtra("status", -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                setBatteryLevel(level);
            }
        };
        batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        mContext.registerReceiver(batteryLevelRcvr, batteryLevelFilter);
    }

    public void setBatteryLevel(int level) {
        SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.BATTERYSTATECALLBACK, level + "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sdkInstance.onDestroy(this);
        //moriLister.disable();
        unregisterReceiver(batteryLevelRcvr);
    }

    @Override
    public void onResume() {
        sdkInstance.onResume(this);
        super.onResume();
        UMGameAgent.onResume(this);
        registerReceiver(rssiReceiver, new IntentFilter(WifiManager.RSSI_CHANGED_ACTION));
    }

    @Override
    public void onPause() {
        super.onPause();
        sdkInstance.onPause(this);
        UMGameAgent.onPause(this);
        unregisterReceiver(rssiReceiver);
    }

    public enum AndroidPhoneType {
        NONE,
        // 华为
        HuaWei,
        // 小米
        XiaoMi,
        // oppo
        OPPO,
        // vivo
        VIVO
    }

    public final String DISPLAY_NOTCH_STATUS = "display_notch_status";
    private String LogTag = "Unity";
    private String istrueString = "true";
    private String isfalseString = "false";

    /*
     * 开始检测设备的刘海屏
     */
    public void StartScreenAdapation(Context curContext) {
        String phoneModel = GetManufature();
        AndroidPhoneType type = GetAndroidPhoneType(phoneModel);
        Log.i(LogTag, "StartScreenAdapation phoneUpperModel:" + phoneModel + "  type:" + type);
        switch (type) {
            case HuaWei:
                huaWeiScreenAdaptation(curContext);
                break;
            case XiaoMi:
                xiaomiScreenAdaptation(curContext);
                break;
            case OPPO:
                oppoScreenAdaptation(curContext);
                break;
            case VIVO:
                vivoScreenAdaptation(curContext);
                break;
            default:
                break;
        }
    }

    @SuppressLint("DefaultLocale")
    private AndroidPhoneType GetAndroidPhoneType(String phoneModel) {
        AndroidPhoneType type = AndroidPhoneType.NONE;
        String phoneUpperModel = phoneModel.toUpperCase();

        Log.i(LogTag, "phoneUpperModel:" + phoneUpperModel);

        if (phoneUpperModel.contains("HUAWEI")) {
            type = AndroidPhoneType.HuaWei;
        } else if (phoneUpperModel.contains("XIAOMI")) {
            type = AndroidPhoneType.XiaoMi;
        } else if (phoneUpperModel.contains("OPPO")) {
            type = AndroidPhoneType.OPPO;
        } else if (phoneUpperModel.contains("VIVO")) {
            type = AndroidPhoneType.VIVO;
        }

        Log.i(LogTag, "type:" + type);
        return type;
    }

    /*
     * 获取手机型号
     */
    private String GetModel() {
        String str = android.os.Build.MODEL;
        Log.i(LogTag, str);
        return str;
    }

    /*
     * 获取手机制造商
     */
    private String GetManufature() {
        String str = android.os.Build.MANUFACTURER;
        Log.i(LogTag, "GetManufature:" + str);
        return str;
    }

    private void huaWeiScreenAdaptation(Context curContext) {
        if (hasNotchInScreen_huawei(curContext)) {
            int[] iwh = getNotchSize_huawei(curContext);
            Log.i(LogTag, "Huawei Notch Size" + iwh[0] + "|" + iwh[1]);
            SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.NOTCHCALLBACK, istrueString + "|" + iwh[1]);
        } else {
            Log.i(LogTag, "Not Huawei Notch！");
            SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.NOTCHCALLBACK, isfalseString);
        }
    }

    /*
     * 是否是刘海屏手机： true：是刘海屏 false：非刘海屏
     */
    @SuppressLint("DefaultLocale")
    @SuppressWarnings("finally")
    private boolean hasNotchInScreen_huawei(Context context) {
        boolean ret = false;
        try {
            ClassLoader cl = context.getClassLoader();
            Class<?> HwNotchSizeUtil = cl.loadClass("com.huawei.android.util.HwNotchSizeUtil");
            Method get = HwNotchSizeUtil.getMethod("hasNotchInScreen");
            Object obj = get.invoke(HwNotchSizeUtil);
            Log.e(LogTag, "hasNotchInScreen_huawei obj:" + obj.toString());
            if (obj != null)
                ret = obj.toString().toUpperCase().equals("TRUE") ? true : false;
            Log.e(LogTag, "hasNotchInScreen_huawei ret:" + ret);
        } catch (ClassNotFoundException e) {
            Log.e(LogTag, "error hasNotchInScreen_huawei ClassNotFoundException");
        } catch (NoSuchMethodException e) {
            Log.e(LogTag, "error hasNotchInScreen_huawei NoSuchMethodException");
        } catch (Exception e) {
            Log.e(LogTag, "error hasNotchInScreen_huawei Exception:" + e.getMessage());
        } finally {
            return ret;
        }
    }

    /*
     * 获取刘海尺寸：width、height int[0]值为刘海宽度 int[1]值为刘海高度
     */
    @SuppressWarnings("finally")
    private int[] getNotchSize_huawei(Context context) {
        int[] ret = new int[]{0, 0};
        try {
            ClassLoader cl = context.getClassLoader();
            Class<?> HwNotchSizeUtil = cl.loadClass("com.huawei.android.util.HwNotchSizeUtil");
            Method get = HwNotchSizeUtil.getMethod("getNotchSize");
            ret = (int[]) get.invoke(HwNotchSizeUtil);
        } catch (ClassNotFoundException e) {
            Log.e(LogTag, "error getNotchSize ClassNotFoundException");
        } catch (NoSuchMethodException e) {
            Log.e(LogTag, "error getNotchSize NoSuchMethodException");
        } catch (Exception e) {
            Log.e(LogTag, "error getNotchSize Exception:" + e.getMessage());
        } finally {
            return ret;
        }
    }

    /*
     * 小米刘海判断
     */
    private void xiaomiScreenAdaptation(Context context) {
        if (hasNotchInScreen_Xiaomi(context)) {
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                int result = context.getResources().getDimensionPixelSize(resourceId);
                SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.NOTCHCALLBACK, istrueString + "|" + result);
                Log.e(LogTag, "xiaomiScreenAdaptation result:" + result);
            }
            Log.e(LogTag, "xiaomiScreenAdaptation resourceId:" + resourceId);
        } else {
            SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.NOTCHCALLBACK, isfalseString);
            Log.i(LogTag, "Not Xiaomi Notch！");
        }
    }

    @SuppressWarnings("finally")
    private boolean hasNotchInScreen_Xiaomi(Context context) {
        boolean result = false;
        try {
            ClassLoader cl = context.getClassLoader();
            Class<?> systemPro = cl.loadClass("android.os.SystemProperties");
            Method get = systemPro.getMethod("get", String.class);
            Object obj = (get.invoke(systemPro, "ro.miui.notch"));
            if (obj != null)
                result = (String) obj == "1" ? true : false;
            Log.e(LogTag, "hasNotchInScreen_Xiaomi Result:" + result);
        } catch (ClassNotFoundException e) {
            Log.e(LogTag, "error hasNotchInScreen_Xiaomi ClassNotFoundException");
        } catch (NoSuchMethodException e) {
            Log.e(LogTag, "error hasNotchInScreen_Xiaomi NoSuchMethodException");
        } catch (Exception e) {
            Log.e(LogTag, "error hasNotchInScreen_Xiaomi Exception:" + e.getMessage());
        } finally {
            return result;
        }
    }

    /*
     * OPPO刘海判断
     */
    private void oppoScreenAdaptation(Context context) {
        if (hasNotchInScreen_Oppo(context)) {
            SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.NOTCHCALLBACK, istrueString + "|" + 80);
        } else {
            SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.NOTCHCALLBACK, isfalseString);
        }
    }

    private boolean hasNotchInScreen_Oppo(Context context) {
        boolean result = false;
        if (context.getPackageManager().hasSystemFeature("com.oppo.feature.screen.heteromorphism")) {
            result = true;
        } else {
            result = false;
        }
        return result;
    }

    /*
     * VIVO刘海判断
     */
    private void vivoScreenAdaptation(Context context) {
        if (hasNotchInScreen_Vivo(context)) {
            SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.NOTCHCALLBACK, istrueString + "|" + 80);
            Log.e(LogTag, "vivoScreenAdaptation true");
        } else {
            SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.NOTCHCALLBACK, isfalseString);
            Log.e(LogTag, "vivoScreenAdaptation false");
        }
    }

    private final int NOTCH_IN_SCREEN_VOIO = 0x00000020;// 是否有凹槽
    private final int HAS_CIRCULAR = 0x00000008;//是否有圆角

    @SuppressLint("DefaultLocale")
    @SuppressWarnings("finally")
    private boolean hasNotchInScreen_Vivo(Context context) {
        boolean ret = false;
        try {
            ClassLoader cl = context.getClassLoader();
            Class<?> FtFeature = cl.loadClass("android.util.FtFeature");
            Method get = FtFeature.getMethod("isFeatureSupport", int.class);
            Object obj = get.invoke(FtFeature, NOTCH_IN_SCREEN_VOIO);
            ret = obj.toString().toUpperCase().equals("TRUE") ? true : false;
            Log.e(LogTag, "hasNotchInScreen_Vivo obj:" + obj.toString());
        } catch (ClassNotFoundException e) {
            Log.e(LogTag, "hasNotchInScreen ClassNotFoundException");
        } catch (NoSuchMethodException e) {
            Log.e(LogTag, "hasNotchInScreen NoSuchMethodException");
        } catch (Exception e) {
            Log.e(LogTag, "hasNotchInScreen Exception");
        } finally {
            return ret;
        }
    }


    @TargetApi(28)
    protected void getNotchInfo() {
        final View decorView = ((Activity) mContext).getWindow().getDecorView();
        decorView.post(new Runnable() {
            @Override
            public void run() {
                DisplayCutout displayCutout = decorView.getRootWindowInsets().getDisplayCutout();
                if (displayCutout != null) {
                    float _notchHeight = displayCutout.getSafeInsetLeft();
                    SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.NOTCHCALLBACK, istrueString + "|" + _notchHeight);
                    Log.e(LogTag, "getNotchInfo _notchHeight:" + _notchHeight);
                } else {
                    SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.NOTCHCALLBACK, isfalseString);
                    Log.e(LogTag, "getNotchInfo not notch device");
                }
            }
        });
    }

    @TargetApi(28)
    public void DisplayFullScreen() {
        Window window = ((Activity) mContext).getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        window.setAttributes(lp);
    }


    ///获取权限请求的返回信息---@NonNull
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        sdkInstance.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 300://----------------获取相册权限----
                boolean write = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean read = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                if (grantResults.length > 0 && write && read) {
                    SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.onRequestPermissionsResult, requestCode + "");
                } else {
                    Toast.makeText(this, "用户已拒绝", Toast.LENGTH_SHORT).show();
                }
                break;
        }

    }


    QuickGameManager sdkInstance;
    public String fbLog = "FBLog";
    public boolean isPrintFBlog = true;

    /*
     * Quick登录
     * */
    public void FBLogin() {
        if (isInitEnd == false) {
            isNeedInitLogin = true;
            Log.e(fbLog, "调起FBLogin()1...........初始化..失败..........需要异步登陆..............");
            return;
        }
        if (isPrintFBlog) {
            Log.e(fbLog, "调起FBLogin()1...................................");
        }
        sdkInstance.login(this);
        if (isPrintFBlog) {
            Log.e(fbLog, "调起FBLogin()2......................................");
        }
    }

    boolean isInitEnd;
    boolean isNeedInitLogin;

    /*
     * 设置Quick角色信息
     * */
    public QGRoleInfo SetQGRoleInfo(String roleId, String roleLevel, String roleName, String serverName, String vipLevel) {
        QGRoleInfo roleInfo = new QGRoleInfo();
        roleInfo.setRoleId(roleId);
        roleInfo.setRoleLevel(roleLevel);
        roleInfo.setRoleName(roleName);
        roleInfo.setServerName(serverName);
        roleInfo.setVipLevel(vipLevel);
        if (isPrintFBlog) {
            Log.i(fbLog, "fb 生成角色信息:"
                    + "  roleId=" + roleId
                    + "  roleLevel=" + roleLevel
                    + "  roleName=" + roleName
                    + "  serverName=" + serverName
                    + "  vipLevel=" + vipLevel);
        }
        return roleInfo;
    }

    /*
     * 设置Quick支付信息
     * */
    public QGOrderInfo SetQGOrderInfo(String OrderSubject, String orderId, String extra_paras, double amount, String callback, String goodsId) {
        QGOrderInfo orderInfo = new QGOrderInfo();
        orderInfo.setOrderSubject(OrderSubject);
        orderInfo.setProductOrderId(orderId);
        orderInfo.setExtrasParams(extra_paras);
        orderInfo.setAmount(amount);
        orderInfo.setCallbackURL(callback);
        orderInfo.setSuggestCurrency("USD");
        String tempId = "";
        if (!goodsId.contains("jzcq")) {
            //tempId = "com.rxgscd.0" + (Integer.valueOf(goodsId) + 1);
            tempId = "jzcq.m" + (Integer.valueOf(goodsId) + 1) + ".com";
        } else {
            tempId = goodsId;
        }
        orderInfo.setGoodsId(tempId);
        if (isPrintFBlog) {
            Log.e(fbLog, "fb 生成支付信息:"
                    + "  OrderSubject=" + OrderSubject
                    + "  orderId=" + orderId
                    + "  extra_paras=" + extra_paras
                    + "  amount=" + amount
                    + "  callback=" + callback
                    + "  goodsId=" + goodsId
                    + "  tempId=" + tempId);
        }
        return orderInfo;
    }

    /*
     * Quick支付
     * */
    public void FBPay(QGOrderInfo orderInfo, QGRoleInfo roleInfo) {
        if (isPrintFBlog) {
            Log.e(fbLog, "fb 开始调起支付:");
        }
        if (isPrintFBlog) {
            if (orderInfo != null) {
                Log.e(fbLog, "fb 传给SDK的支付信息:"
                        + "  OrderSubject=" + orderInfo.getOrderSubject()
                        + "  orderId=" + orderInfo.getProductOrderId()
                        + "  extra_paras=" + orderInfo.getExtrasParams()
                        + "  amount=" + orderInfo.getAmount()
                        + "  callback=" + orderInfo.getCallbackURL()
                        + "  goodsId=" + orderInfo.getGoodsId());
            }
            if (roleInfo != null) {
                Log.e(fbLog, "fb 传给SDK的角色信息:"
                        + "  roleId=" + roleInfo.getRoleId()
                        + "  roleLevel=" + roleInfo.getRoleLevel()
                        + "  roleName=" + roleInfo.getRoleName()
                        + "  serverName=" + roleInfo.getServerName()
                        + "  vipLevel=" + roleInfo.getVipLevel());
            }
        }

        if (orderInfo == null || roleInfo == null) {
            if (isPrintFBlog) {
                Log.i(fbLog, "fb 传入支付参数有空");
            }
            return;
        }

        SamplePaymentCallback paymentCallback = new SamplePaymentCallback();
        sdkInstance.pay(this, orderInfo, roleInfo, paymentCallback);
    }

    /*
     * 更新Quick角色信息
     * */
    public void FBUpdateRoleInfo(QGRoleInfo roleInfo) {
        if (isPrintFBlog) {
            Log.e(fbLog, "fb 更新用户信息");
        }
        sdkInstance.updateRoleInfo(false, roleInfo);
    }

    /*
     * 退出Quick账号
     * */
    public void FBLogout() {
        if (isPrintFBlog) {
            Log.e(fbLog, "fb调起登出..................................................");
        }
        sdkInstance.logout(this);
    }


    /*
     * QuickSDK登录回调
     * */
    private class SampleSDKCallback implements SDKCallback {

        @Override
        public void onLoginFinished(QGUserData userData, QGUserHolder loginState) {
            if (loginState.getStateCode() == QGUserHolder.LOGIN_SUCCESS) {
                //登录成功
                String uid = userData.getUid(); //作为唯一标示
                String displayuid = userData.getdisplayUid();//迁移账号使用，唯一标识
                String token = userData.getToken();
                //判断登录方式: 6:Facebook,8:Google,9:Naver,10:Twitter,11:Line,12:迁移码,14:VK
                //int logintype = Integer.valueOf(userData.getOpenType());
                //判断是否为游客
                //boolean isGuest = userData.isGuest();
                if (isPrintFBlog) {
                    Log.i(fbLog, "FB登录成功>uid:" + userData.getUid() + " displayUid>:" + userData.getdisplayUid() + " token>:" + userData.getToken());// +" logintype>:" + logintype  +" isGuest>:" + isGuest
                }

                //SDKUtility.SendMessage(SDKUtility.CALLBACKFUNCTIONNAME.LOGINCALLBACK, token + "|" + uid);
                API.S_SendMessage(10, "LoginSuccess", token, uid, "");
                QGRoleInfo roleInfo = new QGRoleInfo();
                sdkInstance.submitRoleInfo(uid, roleInfo);
            } else {
                if (isPrintFBlog) {
                    Log.e(fbLog, "FB登录失败");
                }
            }
        }

        @Override
        public void onInitFinished(boolean isSuccess) {
            if (isSuccess) {
                if (isPrintFBlog) {
                    Log.i(fbLog, "FB初始化 成功 开始登陆");
                    QGLog.setDebugMod(true);
                    isInitEnd = true;
                    if (isNeedInitLogin) {
                        isNeedInitLogin = false;
                        Log.e(fbLog, "..初始化.终于完成..........开始异步登陆..............");
                        FBLogin();
                    }
                }
            } else {
                if (isPrintFBlog) {
                    Log.e(fbLog, "FB初始化失败.......");
                }
                S_init_sdk();
            }
        }

        @Override
        public void onLogout() {
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (isPrintFBlog) {
                        Log.i(fbLog, "FB 退出登录");
                    }
                }
            });
        }

        @Override
        public void onGooglePlaySub(String productId, String sdkOrder, boolean isAutoRenewing, boolean isAcknowledged) {
            Log.d(fbLog, "商品id=" + productId + "&&sdkOrder=" + sdkOrder + "&&是否订阅=" + isAutoRenewing + "&&是否确认" + isAcknowledged);
        }
    }

    /*
     * QuickSDK支付回调
     * */
    private class SamplePaymentCallback implements QGPaymentCallback {

        @Override
        public void onPaySuccess(String orderId, String orderNo, String extraParams) {
            //返回支付时传入的订单号、SDK订单号和透传参数
            if (isPrintFBlog) {
                Log.i(fbLog, "支付成功....orderNo =" + orderNo + "....orderId =" + orderId + ".....extraParams=" + extraParams);
            }
            FBReportAppPay(API.qgOrderInfo.getProductOrderId(), API.qgOrderInfo.getAmount(), API.qgOrderInfo.getOrderSubject(), API.qgOrderInfo.getGoodsId());
        }

        @Override
        public void onPayFailed(String orderId, String orderNo, String errorMessage) {
            //返回支付时传入的订单号、SDK订单号和错误信息
            if (isPrintFBlog) {
                Log.e(fbLog, "支付失败...orderNo =" + orderNo + "...orderId =" + orderId + "...errorMessage=" + errorMessage);
            }
        }

        @Override
        public void onPayCancel(String orderId, String orderNo, String errorMessage) {
            //返回支付时传入的订单号、SDK订单号和错误信息
            if (isPrintFBlog) {
                Log.e(fbLog, "支付取消orderNo =" + orderNo + "支付取消orderId =" + orderId + " 支付取消errorMessage=" + errorMessage);
            }
        }

    }


    @Override
    protected void onStart() {
        super.onStart();
        sdkInstance.onStart(this);
        Log.e("MainActivity", "onStart");
    }

    @Override
    protected void onStop() {
        super.onStop();
        sdkInstance.onStop(this);
        Log.e("MainActivity", "onStop");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("MainActivity", "onActivityResult");
        super.onActivityResult(requestCode, resultCode, data);
        sdkInstance.onActivityResult(requestCode, resultCode, data);
    }

    /*
     * 上报Quick支付信息
     * */
    public void FBReportAppPay(String orderId, double amount, String goodsName, String goodsId) {
        Map<String, Object> eventValues = new HashMap<>();
        eventValues.put(AFInAppEventParameterName.ORDER_ID, orderId); //订单号,string
        eventValues.put(AFInAppEventParameterName.REVENUE, amount); //价格,float
        eventValues.put(AFInAppEventParameterName.CONTENT_TYPE, goodsName); //商品名,string
        eventValues.put(AFInAppEventParameterName.CONTENT_ID, goodsId); //商品id,string
        eventValues.put(AFInAppEventParameterName.CURRENCY, "USD"); //货币单位,string  CNY：人民币   USD:美元
        AppsFlyerLib.getInstance().trackEvent(getApplicationContext(), AFInAppEventType.PURCHASE, eventValues);
        FBChargeGearReport(amount);
    }

    /*
     * 上报Quick完成新手引导--000
     * */
    public void FBNewGuidFinished() {
        AppsFlyerLib.getInstance().trackEvent(getApplicationContext(), AFInAppEventType.TUTORIAL_COMPLETION, null);
    }

    /*
     * 上报Quick创建角色完成
     * */
    public void FBCreateRoleFinished(String roleId) {
        Map<String, Object> eventValues = new HashMap<>();
        eventValues.put("af_role_id", roleId); //角色id,string
        AppsFlyerLib.getInstance().trackEvent(getApplicationContext(), "af_create_role", eventValues);
    }

    /*
     * 上报Quick领取首充奖励--000
     * */
    public void FBReceiveFirstCahrge() {
        AppsFlyerLib.getInstance().trackEvent(getApplicationContext(), "af_1stpaygift_get", null);
    }

    /*
     * 上报Quick充值挡位
     * */
    public void FBChargeGearReport(double amount) {
        AppsFlyerLib.getInstance().trackEvent(getApplicationContext(), "af_pay_" + (amount * 100), null);
    }
}